<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { ElImage, ElImageViewer } from 'element-plus'
  import { Picture, Star, Clock, Download, Loading } from '@element-plus/icons-vue'
  import { formatDistanceToNow } from 'date-fns'
  import { zhCN } from 'date-fns/locale'
  import { BlogFile, Weibo } from '@/types/api'

  interface Props {
    weibo: Weibo
    isTop?: boolean
  }

  const props = withDefaults(defineProps<Props>(), {
    isTop: false,
  })

  // 图片预览相关
  const showImageViewer = ref(false)
  const imageViewerIndex = ref(0)
  const previewImages = ref<string[]>([])

  // 格式化时间
  const formatTime = (dateString: string) => {
    return formatDistanceToNow(new Date(dateString), {
      addSuffix: true,
      locale: zhCN,
    })
  }

  // 获取图片列表
  const images = computed(() => {
    return (
      props.weibo.files?.filter(
        file =>
          file.extension &&
          (file.extension.startsWith('image/') ||
            file.extension.includes('jpeg') ||
            file.extension.includes('jpg') ||
            file.extension.includes('png') ||
            file.extension.includes('gif') ||
            file.extension.includes('webp') ||
            file.extension.includes('svg'))
      ) || []
    )
  })

  // 获取非图片文件列表
  const otherFiles = computed(() => {
    return (
      props.weibo.files?.filter(
        file =>
          !file.extension ||
          (!file.extension.startsWith('image/') &&
            !file.extension.includes('jpeg') &&
            !file.extension.includes('jpg') &&
            !file.extension.includes('png') &&
            !file.extension.includes('gif') &&
            !file.extension.includes('webp') &&
            !file.extension.includes('svg'))
      ) || []
    )
  })

  // 获取图片URL，优先使用portalUrl，fallback到url
  const getImageUrl = (file: BlogFile): string => {
    if (file.portalUrl) {
      return file.portalUrl
    }
    if (file.url) {
      return file.url
    }
    // 如果都没有，尝试构造URL
    if (file.fileName) {
      return `/api/portal/file/${file.fileName}`
    }
    return ''
  }

  // 处理图片预览
  const handleImagePreview = (index: number) => {
    previewImages.value = images.value.map(img => getImageUrl(img))
    imageViewerIndex.value = index
    showImageViewer.value = true
  }

  // 关闭图片预览
  const closeImageViewer = () => {
    showImageViewer.value = false
    previewImages.value = []
    imageViewerIndex.value = 0
  }

  // 处理内容中的链接和换行
  const formatContent = (content: string) => {
    return content
      .replace(/\n/g, '<br>')
      .replace(
        /(https?:\/\/[^\s]+)/g,
        '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'
      )
      .replace(/#([^#\s]+)#/g, '<span class="hashtag">#$1#</span>')
  }

  // 获取文件大小显示
  const getFileSize = (size: number) => {
    if (size < 1024) return `${size}B`
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`
    return `${(size / (1024 * 1024)).toFixed(1)}MB`
  }

  // 获取文件图标
  const getFileIcon = (extension: string) => {
    if (extension.includes('pdf')) return '📄'
    if (extension.includes('word') || extension.includes('doc')) return '📝'
    if (extension.includes('excel') || extension.includes('sheet')) return '📊'
    if (extension.includes('powerpoint') || extension.includes('presentation')) return '📈'
    if (extension.includes('zip') || extension.includes('rar')) return '📦'
    if (extension.includes('video')) return '🎬'
    if (extension.includes('audio')) return '🎵'
    return '📎'
  }

  // 图片加载错误处理
  const handleImageError = (event: Event) => {
    console.warn('图片加载失败:', event)
  }

  // 获取图片网格布局辅助类名
  const getImageItemClass = (index: number, count: number) => {
    if (count === 3 && index === 0) return 'main-img'
    if (count === 5 && index === 0) return 'main-img'
    return ''
  }
</script>

<template>
  <div class="moment-card" :class="{ 'is-top': isTop }">
    <!-- 置顶标识 -->
    <div v-if="isTop" class="top-badge">
      <el-icon><Star /></el-icon>
      <span>置顶</span>
    </div>

    <!-- 卡片内容 -->
    <div class="card-content">
      <!-- 文字内容 -->
      <div v-if="weibo.content" class="moment-text">
        <div class="text-content" v-html="formatContent(weibo.content)"></div>
      </div>

      <!-- 图片展示 -->
      <div v-if="images.length > 0" class="moment-images">
        <div class="images-grid" :class="`img-count-${images.length}`">
          <template v-for="(image, index) in images.slice(0, 9)" :key="image.id || index">
            <div
              class="image-item"
              :class="getImageItemClass(index, images.length)"
              @click="handleImagePreview(index)"
            >
              <ElImage
                :src="getImageUrl(image)"
                :alt="image.originalName || `图片${index + 1}`"
                fit="contain"
                class="moment-image"
                lazy
                loading="lazy"
                @error="handleImageError"
              >
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                    <span>加载中...</span>
                  </div>
                </template>
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </ElImage>
              <div v-if="index === 8 && images.length > 9" class="more-images-overlay">
                <span>+{{ images.length - 9 }}</span>
              </div>
            </div>
          </template>
        </div>
        <div v-if="images.length > 1" class="image-counter">
          <el-icon><Picture /></el-icon>
          <span>{{ images.length }} 张图片</span>
        </div>
      </div>

      <!-- 其他文件 -->
      <div v-if="otherFiles.length > 0" class="moment-files">
        <div class="files-header">
          <div class="files-title">
            <el-icon><Download /></el-icon>
            <span>附件 ({{ otherFiles.length }})</span>
          </div>
        </div>
        <div class="files-list">
          <a
            v-for="file in otherFiles"
            :key="file.id"
            :href="getImageUrl(file)"
            target="_blank"
            class="file-item"
            :title="`下载 ${file.originalName}`"
          >
            <div class="file-icon">{{ getFileIcon(file.extension) }}</div>
            <div class="file-info">
              <div class="file-name">{{ file.originalName }}</div>
              <div class="file-meta">
                <span class="file-size">{{ getFileSize(file.fileSize) }}</span>
                <span class="file-type">{{ file.extension || '未知类型' }}</span>
              </div>
            </div>
            <div class="file-download">
              <el-icon><Download /></el-icon>
            </div>
          </a>
        </div>
      </div>

      <!-- 时间信息 -->
      <div class="moment-meta">
        <div class="time-info">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(weibo.createTime) }}</span>
        </div>
      </div>
    </div>

    <!-- 图片预览器 -->
    <ElImageViewer
      v-if="showImageViewer"
      :url-list="previewImages"
      :initial-index="imageViewerIndex"
      hide-on-click-modal
      teleported
      @close="closeImageViewer"
    />
  </div>
</template>

<style lang="scss" scoped>
  .moment-card {
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    padding: 1.5rem;
    position: relative;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    &:hover {
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      transform: translateY(-4px);
    }

    &.is-top {
      border-color: var(--warning-color);
      background: linear-gradient(135deg, var(--bg-color) 0%, rgba(255, 193, 7, 0.03) 100%);
    }
  }

  .top-badge {
    position: absolute;
    top: -1px;
    right: -1px;
    background: var(--warning-color);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 0 var(--radius-lg) 0 var(--radius-md);
    font-size: 0.75rem;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 0.25rem;
    z-index: 1;
  }

  .card-content {
    .moment-text {
      margin-bottom: 1.2rem;

      .text-content {
        font-size: 1rem;
        line-height: 1.7;
        color: var(--text-primary);
        word-break: break-word;

        :deep(br) {
          display: block;
          margin: 0.5rem 0;
        }

        :deep(a) {
          color: var(--primary-color);
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }

        :deep(.hashtag) {
          color: var(--primary-color);
          font-weight: 600;
          background: var(--primary-light);
          padding: 0.1rem 0.3rem;
          border-radius: var(--radius-sm);
        }
      }
    }

    .moment-images {
      margin-bottom: 1rem;
      .images-grid {
        display: grid;
        gap: 4px;
        border-radius: 8px;
        overflow: hidden;
        &.img-count-1 {
          grid-template-columns: 1fr;
          .image-item {
            aspect-ratio: 16/9;
          }
        }
        &.img-count-2 {
          grid-template-columns: 1fr 1fr;
          .image-item {
            aspect-ratio: 1/1;
          }
        }
        &.img-count-3 {
          grid-template-columns: 2fr 1fr;
          grid-template-rows: 1fr 1fr;
          .image-item {
            aspect-ratio: 1/1;
          }
          .main-img {
            grid-row: 1 / span 2;
            grid-column: 1 / 2;
            aspect-ratio: 3/4;
          }
        }
        &.img-count-4 {
          grid-template-columns: 1fr 1fr;
          grid-template-rows: 1fr 1fr;
          .image-item {
            aspect-ratio: 1/1;
          }
        }
        &.img-count-5 {
          grid-template-columns: 2fr 1fr 1fr;
          grid-template-rows: 1fr 1fr;
          .image-item {
            aspect-ratio: 1/1;
          }
          .main-img {
            grid-row: 1 / span 2;
            grid-column: 1 / 2;
            aspect-ratio: 3/4;
          }
        }
        &.img-count-6 {
          grid-template-columns: repeat(3, 1fr);
          grid-template-rows: repeat(2, 1fr);
          .image-item {
            aspect-ratio: 1/1;
          }
        }
        &.img-count-7,
        &.img-count-8,
        &.img-count-9 {
          grid-template-columns: repeat(3, 1fr);
          grid-template-rows: repeat(3, 1fr);
          .image-item {
            aspect-ratio: 1/1;
          }
        }
      }
      .image-item {
        position: relative;
        cursor: pointer;
        border-radius: 8px;
        overflow: hidden;
        background: var(--bg-secondary);
        .moment-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
          transition: all 0.3s;
        }
        &:hover .moment-image {
          transform: scale(1.04);
        }
        .image-placeholder,
        .image-error {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          background: var(--bg-secondary);
          color: var(--text-secondary);
          font-size: 0.8rem;
          .loading-icon {
            font-size: 1.2rem;
            margin-bottom: 0.5rem;
            animation: spin 1s linear infinite;
          }
        }
        .more-images-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 1.5rem;
          font-weight: 700;
          backdrop-filter: blur(2px);
        }
      }
      .image-counter {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-top: 0.75rem;
        font-size: 0.85rem;
        color: var(--text-secondary);
      }
    }

    .moment-files {
      margin-bottom: 1rem;
      background: var(--bg-secondary);
      border-radius: var(--radius-md);
      overflow: hidden;

      .files-header {
        padding: 0.75rem 1rem;
        border-bottom: 1px solid var(--border-color);
        background: var(--bg-color);

        .files-title {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          font-size: 0.9rem;
          font-weight: 600;
          color: var(--text-primary);
        }
      }

      .files-list {
        padding: 0.5rem;
      }

      .file-item {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem;
        background: var(--bg-color);
        border-radius: var(--radius-sm);
        text-decoration: none;
        color: var(--text-primary);
        transition: all 0.2s ease;
        margin-bottom: 0.5rem;

        &:last-child {
          margin-bottom: 0;
        }

        &:hover {
          background: var(--primary-light);
          transform: translateX(4px);

          .file-download {
            opacity: 1;
            transform: scale(1.1);
          }
        }

        .file-icon {
          font-size: 1.8rem;
          flex-shrink: 0;
        }

        .file-info {
          flex: 1;
          min-width: 0;

          .file-name {
            font-size: 0.9rem;
            font-weight: 500;
            color: var(--text-primary);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 0.2rem;
          }

          .file-meta {
            display: flex;
            gap: 1rem;
            font-size: 0.75rem;
            color: var(--text-secondary);

            .file-type {
              text-transform: uppercase;
            }
          }
        }

        .file-download {
          opacity: 0.6;
          transition: all 0.2s ease;
          color: var(--primary-color);
        }
      }
    }

    .moment-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 0.75rem;
      border-top: 1px solid var(--border-color);

      .time-info {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        color: var(--text-secondary);
        font-size: 0.85rem;
      }
    }
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .moment-card {
      padding: 1rem;
    }
    .moment-images .images-grid {
      grid-template-columns: repeat(2, 1fr) !important;
      grid-template-rows: unset !important;
      .image-item,
      .main-img {
        aspect-ratio: 1/1 !important;
        grid-row: unset !important;
        grid-column: unset !important;
      }
    }
    .moment-files {
      .files-header {
        padding: 0.5rem 0.75rem;
      }

      .files-list {
        padding: 0.25rem;
      }

      .file-item {
        padding: 0.5rem;
      }
    }
  }
</style>
